ConsumeVoucherAction   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 3
eloc 34
dl 0
loc 37
rs 10
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A index 0 27 3
1
import {
2
  Controller,
3
  Inject,
4
  Post,
5
  Body,
6
  BadRequestException,
7
  Param
8
} from '@nestjs/common';
9
import { ApiTags, ApiOperation } from '@nestjs/swagger';
10
import { ICommandBus } from 'src/Application/ICommandBus';
11
import { CreateUserCommand } from 'src/Application/User/Command/CreateUserCommand';
12
import { UserView } from 'src/Application/User/View/UserView';
13
import { IQueryBus } from 'src/Application/IQueryBus';
14
import { GetVoucherByCodeQuery } from 'src/Application/School/Query/Voucher/GetVoucherByCodeQuery';
15
import { VoucherView } from 'src/Application/School/View/VoucherView';
16
import { ConsumeVoucherDTO } from '../../DTO/ConsumeVoucherDTO';
17
import { UserRole } from 'src/Domain/User/User.entity';
18
import { RemoveVoucherCommand } from 'src/Application/School/Command/Voucher/RemoveVoucherCommand';
19
import { AddUserToSchoolCommand } from 'src/Application/School/Command/User/AddUserToSchoolCommand';
20
21
@Controller('vouchers')
22
@ApiTags('School voucher')
23
export class ConsumeVoucherAction {
24
  constructor(
25
    @Inject('ICommandBus')
26
    private readonly commandBus: ICommandBus,
27
    @Inject('IQueryBus')
28
    private readonly queryBus: IQueryBus
29
  ) {}
30
31
  @Post(':code/consume')
32
  @ApiOperation({ summary: 'Consume voucher' })
33
  public async index(
34
    @Param('code') code: string,
35
    @Body() { firstName, lastName, password }: ConsumeVoucherDTO
36
  ): Promise<UserView> {
37
    try {
38
      const voucher: VoucherView = await this.queryBus.execute(new GetVoucherByCodeQuery(code));
39
      if (!voucher) {
40
        return;
41
      }
42
43
      const id = await this.commandBus.execute(
44
        new CreateUserCommand(
45
          firstName,
46
          lastName,
47
          voucher.email,
48
          password,
49
          UserRole.DIRECTOR
50
        )
51
      );
52
53
      await this.commandBus.execute(new AddUserToSchoolCommand(id, voucher.schoolId));
54
      await this.commandBus.execute(new RemoveVoucherCommand(voucher.id));
55
    } catch (e) {
56
      throw new BadRequestException(e.message);
57
    }
58
  }
59
}
60